package com.htx.zqs.blesmartmask.ui.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothGatt;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.data.BleScanState;
import com.clj.fastble.exception.BleException;
import com.google.gson.Gson;
import com.htx.zqs.blesmartmask.MyApplication;
import com.htx.zqs.blesmartmask.R;
import com.htx.zqs.blesmartmask.bean.BeforeCourseData;
import com.htx.zqs.blesmartmask.bean.BleDeviceBean;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.bean.EventBean;
import com.htx.zqs.blesmartmask.bean.LimitInfo;
import com.htx.zqs.blesmartmask.eventbus.BleDataEvent;
import com.htx.zqs.blesmartmask.eventbus.MessageEvent;
import com.htx.zqs.blesmartmask.listeners.BleNotifyListener;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.htx.zqs.blesmartmask.ui.activity.MainActivity;
import com.htx.zqs.blesmartmask.ui.activity.StartCourseActivity;
import com.htx.zqs.blesmartmask.ui.activity.TestWaterActivity;
import com.htx.zqs.blesmartmask.ui.base.BaseFragment;
import com.htx.zqs.blesmartmask.ui.fragment.adapter.DeviceNewAdapter;
import com.htx.zqs.blesmartmask.utils.AlertUtils;
import com.htx.zqs.blesmartmask.utils.BleUtils;
import com.htx.zqs.blesmartmask.utils.Constants;
import com.htx.zqs.blesmartmask.utils.EventBusUtil;
import com.htx.zqs.blesmartmask.utils.Logger;
import com.htx.zqs.blesmartmask.utils.OkhttpUtils;
import com.htx.zqs.blesmartmask.utils.SPUtil;
import com.htx.zqs.blesmartmask.utils.MySpUtils;
import com.htx.zqs.blesmartmask.utils.ToastUtils;
import com.htx.zqs.blesmartmask.utils.Utils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.reactivestreams.Subscription;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.InjectView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;

/**
 * Created by KomoriWu
 * 连接设置
 * on 2019/2/17.
 */
public class DeviceNewFragment extends BaseFragment implements OnRefreshListener {
    public static final String TAG = DeviceNewFragment.class.getSimpleName();
    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    @InjectView(R.id.rv_device)
    RecyclerView rvDevice;
    @InjectView(R.id.swipeRefreshLayout)
    SmartRefreshLayout swipeRefreshLayout;
    @InjectView(R.id.progress)
    ProgressBar progress;
    private DeviceNewAdapter mAdapter;
    private String deviceId;
    private String mLastCourseName;
    private int mLimitCourseCount;
    private byte[] keyDecode = new byte[5];
    private ImageView ivConned;

    @Override
    public boolean isRegisterEvent() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_device;
    }

    @Override
    public void init() {
        initRecyclerView();
        swipeRefreshLayout.autoRefresh();
    }

    private void checkPermissions() {
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(activity, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Utils.checkGPSIsOpen(activity)) {
                    openGps();
                }
                scanBle();
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(activity, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    //扫描ble
    private void scanBle() {
        if (!BleManager.getInstance().isBlueEnable()) {
            //强行打开蓝牙
            BleManager.getInstance().enableBluetooth();
        }
        if (BleManager.getInstance().getScanSate() == BleScanState.STATE_SCANNING) {
            BleManager.getInstance().cancelScan();
        }
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                clearScanDevice();
                addConnedDevice();
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                Timber.d("onScanning:" + bleDevice.getMac() + "  isConn:" + BleManager.
                        getInstance().isConnected(bleDevice));
                boolean isAdd = true;
                for (BleDeviceBean bleDevice1 : mAdapter.getData()) {
                    if (TextUtils.equals(bleDevice1.getBleDevice().getMac(), bleDevice.getMac())) {
                        //设备列表已存在
                        isAdd = false;
                        break;
                    }
                }
                if (isAdd) {
                    mAdapter.addData(new BleDeviceBean(bleDevice));
                }
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                Timber.d("onScanFinished:" + scanResultList.size());
            }
        });
    }

    private void openGps() {
        AlertUtils.showAlertDialog(activity, R.string.kindly_reminder_, R.string.
                        cancel1, R.string.setting, getString(R.string.gpsNotifyMsg),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (which == DialogInterface.BUTTON_POSITIVE) {
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                        }
                    }
                });
    }

    private void initRecyclerView() {
        swipeRefreshLayout.setEnableRefresh(true);
        swipeRefreshLayout.setEnableLoadMore(false);
        swipeRefreshLayout.setOnRefreshListener(this);
        rvDevice.setLayoutManager(new LinearLayoutManager(activity));
        mAdapter = new DeviceNewAdapter(activity);
        rvDevice.setAdapter(mAdapter);
        ((DefaultItemAnimator) rvDevice.getItemAnimator()).setSupportsChangeAnimations(false);
        View view = LayoutInflater.from(activity).inflate(R.layout.header_conn_device, null);
        mAdapter.addHeaderView(view);
        mAdapter.bindToRecyclerView(rvDevice);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                BleDeviceBean bleDevice = (BleDeviceBean) adapter.getItem(position);
                if (bleDevice == null) return;
                ivConned = (ImageView) adapter.getViewByPosition(rvDevice, position + 1,
                        R.id.iv_conned);
                if (ivConned == null) return;
                if (ivConned.getVisibility() == View.VISIBLE) {
                    if (!BleManager.getInstance().isConnected(bleDevice.getBleDevice())) {
                        ivConned.setVisibility(View.INVISIBLE);
                    }
                    //断开
                    BleManager.getInstance().disconnect(bleDevice.getBleDevice());
                } else {
                    //去连接
                    connBle(bleDevice.getBleDevice());
                }
            }
        });
    }

    private void connBle(BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                progress.setVisibility(View.VISIBLE);
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Logger.d(TAG,"连接失败"+ bleDevice.getMac());
                progress.setVisibility(View.GONE);
                ToastUtils.show(activity, R.string.conn_fail);
                //连接失败刷新列表
                scanBle();
            }

            @SuppressLint("CheckResult")
            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //加密验证
                Logger.d(TAG,"连接成功"+ bleDevice.getMac());
//                keyDecode = new byte[9];
                BleUtils.write(bleDevice, BleUtils.getDefaultKeyCommand(), null);
//                BleUtils.stopNotify(bleDevice);
                toVerifyKey(bleDevice);
//                BleManager.getInstance().notify(bleDevice, BleUtils.UUID_SERVICE,
//                        BleUtils.UUID_CHARACTERISTIC_NOTIFY, new BleNotifyCallback() {
//                            @Override
//                            public void onNotifySuccess() {
//                                Timber.d("打开通知成功：" + bleDevice.getMac());
//
//                            }
//
//                            @Override
//                            public void onNotifyFailure(BleException exception) {
//                                progress.setVisibility(View.GONE);
//                                ToastUtils.show(activity, R.string.conn_fail);
//                            }
//
//                            @Override
//                            public void onCharacteristicChanged(byte[] data) {
//                                Timber.d("notify by mac:" + bleDevice.getMac() + "---data:" +
//                                        Utils.bytesToHexString(data));
//                                //41  54  2d  59  d1  d5  8c  b6  b2
//                                if (TextUtils.equals(Utils.bytesToHexString(data),Utils.bytesToHexString(keyDecode))) {
//                                    BleUtils.stopNotify(bleDevice);
//                                    toVerifyKey(ivConned, bleDevice);
//                                }
//
//                            }
//                        });

            }

            @SuppressLint("CheckResult")
            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
                Logger.d(TAG,"断开连接"+ bleDevice.getMac());
                //断开连接取消电量显示
                for (int i = 0; i < mAdapter.getData().size(); i++) {
                    if (bleDevice.getMac().equals(mAdapter.getData().get(i).getBleDevice().getMac())) {
                        ImageView ivConned = (ImageView) mAdapter.getViewByPosition(i + 1,
                                R.id.iv_conned);
                        ImageView ivElectric = (ImageView) mAdapter.getViewByPosition(i + 1,
                                R.id.iv_electric);
                        TextView tvCourse = (TextView) mAdapter.getViewByPosition(i + 1,
                                R.id.tv_course);
                        if (ivConned == null || ivElectric == null || tvCourse == null) return;
                        ivConned.setVisibility(View.INVISIBLE);
                        ivElectric.setVisibility(View.INVISIBLE);
                        tvCourse.setVisibility(View.INVISIBLE);
                        break;
                    }
                }
            }
        });
    }


    private void toVerifyKey(final BleDevice bleDevice) {
        ivConned.setVisibility(View.VISIBLE);
        progress.setVisibility(View.GONE);
        //显示电量
        BleUtils.notify(bleDevice, new BleNotifyListener() {
            @SuppressLint({"StringFormatInvalid", "StringFormatMatches"})
            @Override
            public void onSuccess(byte[] data) {
                if (data[3] == 77) {
                    dealUseNum(data, bleDevice);
                } else {
                    showElectric(data, bleDevice);
                    Utils.showSleepDialog(data[16]);
                }
            }
        });

        boolean isFirst = BleManager.getInstance().getAllConnectedDevice().size() == 1;
        if (isFirst) {
            MySpUtils.putString(MySpUtils.KEY_FIRST_DEVICE, bleDevice.getMac());
            //第一个设备时，才发送
            BleUtils.write(bleDevice, BleUtils.getSerialNumCommand(), new BleWriteCallback() {
                @SuppressLint("CheckResult")
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    MySpUtils.putString(MySpUtils.KEY_FIRST_DEVICE, bleDevice.getMac());
                    ToastUtils.show(activity, R.string.first_device_hint);

                    //获取设备使用时间、次数
                    Flowable.just("")
                            .delay(3, TimeUnit.SECONDS)
                            .subscribe(new Consumer<String>() {
                                @Override
                                public void accept(String s) {
                                    getUseTimes(bleDevice);
                                }
                            });
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        }
    }

    private void dealUseNum(byte[] data, BleDevice bleDevice) {
        //41  54  2d  4d  01  93  00  09  0d  0a ,[4][5]转化成十进制 403
        String hex = Utils.bytesToHexString(new byte[]{data[4], data[5]}).
                replaceAll(" ", "");
        int time = (int) Long.parseLong(hex, 16);
        if (time <= 500) {
            //如果为第一个设备则上传使用情况
            MySpUtils.putInt(MySpUtils.KEY_DEVICE_USE_TIME, time);
            MySpUtils.putInt(MySpUtils.KEY_DEVICE_USE_NUM, data[7]);
            EventBus.getDefault().post(new MessageEvent(Constants.EVENT_UP_DEVICE_INFO));
            mIsNewDevice = true;
//                                BleUtils.stopNotify(bleDevice);
            if (time >= Constants.BLE_DEVICE_COUNT_TIME) {
                //设备使用时间达到上限400分钟
                if (BleManager.getInstance().isConnected(bleDevice)) {
                    AlertUtils.showAlertDialog(activity, R.string.kindly_reminder_,
                            getString(R.string.power_low_change_device));
                    BleManager.getInstance().disconnect(bleDevice);
                }
            }
        }
    }

    private void showElectric(byte[] data, BleDevice bleDevice) {
        //65 84 74 81
        String hexData = Utils.bytesToHexString(new byte[]{data[2]});
        if (hexData.contains("4a")) {
            String electricStr = Utils.bytesToHexString(new byte[]{data[15]}).replaceAll(" ", "");
            int electric = Integer.parseInt(electricStr, 16);
            if (electric == 0) return;
            for (int i = 0; i < mAdapter.getData().size(); i++) {
                BleDeviceBean bleDeviceBean = mAdapter.getData().get(i);
                ImageView ivElectric = (ImageView) mAdapter.getViewByPosition(i + 1, R.id.iv_electric);
                if (ivElectric == null) return;
                if (bleDeviceBean.getBleDevice().getMac().equals(bleDevice.getMac()) &&
                        (bleDeviceBean.getElectric() != electric || ivElectric.getVisibility() != View.VISIBLE)) {
                    Logger.d("mac:" + bleDevice.getMac() + "---解析的电量值为electric：" + electric);
                    bleDeviceBean.setElectric(electric);
                    mAdapter.setData(i, bleDeviceBean);
//                    BleUtils.stopNotify(bleDevice);
                    break;
                }
            }

        }
    }

    private boolean mIsNewDevice;//是否为新设备

    @SuppressLint("CheckResult")
    private void getUseTimes(final BleDevice bleDevice) {
        BleUtils.write(bleDevice, BleUtils.getUseTimesCommand(), new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) {
                Flowable.just("")
                        .delay(2, TimeUnit.SECONDS)
                        .subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String s) {
                                if (mIsNewDevice) return;
                                //获取服务器上设备使用信息
                                getDeviceInfo(bleDevice);
                            }
                        });
            }

            @Override
            public void onWriteFailure(BleException exception) {


            }
        });


    }

    private void getDeviceInfo(final BleDevice bleDevice) {
        OkhttpUtils okhttpUtils = new OkhttpUtils(activity, Contants.BLUE_TIME, new OkListener() {
            @SuppressLint("StringFormatInvalid")
            @Override
            public void onSuccess(int requestCode, String string) {
                Gson gson = new Gson();
                LimitInfo limitInfo = gson.fromJson(string, LimitInfo.class);
                LimitInfo.DataBean data = limitInfo.getData();
                Timber.e("获取设备使用情况成功data：" + data.toString());
                if (mIsNewDevice) return;
//                BleUtils.stopNotify(bleDevice);
                MySpUtils.putInt(MySpUtils.KEY_DEVICE_USE_TIME, data.getMin());
                MySpUtils.putInt(MySpUtils.KEY_DEVICE_USE_NUM, data.getNumberlong());

                if (data.getMin() >= Constants.BLE_DEVICE_COUNT_TIME) {
                    //设备使用时间达到上限400分钟
                    if (BleManager.getInstance().isConnected(bleDevice)) {
                        AlertUtils.showAlertDialog(activity, R.string.kindly_reminder_,
                                getString(R.string.power_low_change_device));
                        BleManager.getInstance().disconnect(bleDevice);
                    }
                }
            }

            @Override
            public void onError(int requestCode, IOException e) {

            }
        });
        HashMap map = new HashMap();
        map.put("address", bleDevice.getMac());
        okhttpUtils.postForm(Contants.BLUE_TIME, Contants.URL_BLUE_TIME, map);
    }

    @SuppressLint("CheckResult")
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        swipeRefreshLayout.finishRefresh(2500);
        Flowable.just("")
                .delay(1000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        checkPermissions();
                    }
                });

    }

    //已连接上的设备，不会再扫描到 重启应用时直接将已连接的加到列表中显示
    private void addConnedDevice() {
        if (mAdapter.getData().size() == 0) {
            List<BleDevice> connedDeviceList = BleManager.getInstance().getAllConnectedDevice();
            List<BleDeviceBean> deviceBeanList = new ArrayList<>();
            for (BleDevice bleDevice : connedDeviceList) {
                deviceBeanList.add(new BleDeviceBean(bleDevice));
            }
            mAdapter.addData(deviceBeanList);
        }
    }

    //没有连接上的设备清除掉
    private void clearScanDevice() {
        List<BleDeviceBean> deviceList = mAdapter.getData();
        for (int i = 0; i < deviceList.size(); i++) {
            BleDevice device = deviceList.get(i).getBleDevice();
            if (!BleManager.getInstance().isConnected(device)) {
                deviceList.remove(i);
                i -= 1;
            }
        }
        mAdapter.setNewData(deviceList);
    }

    @OnClick({R.id.testButton, R.id.startButton})
    public void onViewClicked(View view) {
        final BleDevice bleDevice = Utils.getFirstDevice();
        if (bleDevice != null) {
            switch (view.getId()) {
                case R.id.testButton:
                    //测试油水
                    TestWaterActivity.startAct(activity, bleDevice);
                    break;
                case R.id.startButton:
                    try {
                        String name = (String) SPUtil.get(getActivity(), deviceId, "", "mLastCourseName");
                        if (name.equals("")) {
                            mLastCourseName = "";
                        } else {
                            mLastCourseName = MyApplication.getCourseFromIndex(Integer.parseInt(name));
                        }
                    } catch (Exception e) {
                        mLastCourseName = (String) SPUtil.get(getActivity(), deviceId, "", "mLastCourseName");
                    }
                    mLimitCourseCount = (int) SPUtil.get(getContext(), deviceId, 0, "LimitCourseCount");


                    if (!MyApplication.isCourseExist) {
                        new AlertDialog.Builder(getContext()).setTitle(R.string.course_data_no_exit_title)
                                .setMessage(R.string.course_data_no_exit_message)
                                .setPositiveButton(R.string.ok, null)
                                .show();
                    } else {
                        if (mLastCourseName == "") {
                            startCourse();
                        } else {
                            if (MyApplication.selectCourse.getName().equals(mLastCourseName)) {
                                startCourse();
                            } else if (mLimitCourseCount >= Contants.LIMIT_COURSE_COUNT || mLimitCourseCount == 0) {
                                startCourse();
                            } else {
                                new AlertDialog.Builder(getContext()).setTitle(R.string.course_count_no_six_title)
                                        .setMessage(getResources().getString(R.string.cycle_message1) + mLastCourseName +
                                                getResources().getString(R.string.cycle_message2) + mLimitCourseCount + getResources().getString(R.string.cycle_message3))
                                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                changeHomeFragmentUi();
                                            }
                                        })
                                        .show();
                            }
                        }
                    }

                    break;
            }
        } else {
            scanBle();

            //当前没有连接ble
            AlertUtils.showAlertDialog(activity, R.string.blebroadcast_title, R.string.
                            cancel1, R.string.main_bluetooth_go, getString(R.string.blebroadcast_message),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            if (which == DialogInterface.BUTTON_POSITIVE) {
                                swipeRefreshLayout.autoRefresh();
                            }
                        }
                    });
        }

    }

    private void startCourse() {
        final BleDevice bleDevice = Utils.getFirstDevice();
        if (bleDevice == null) return;
        if (MyApplication.bluetoothState == Contants.STATE_NO_RUN) {
            if (MyApplication.isTestWater) {
                StartCourseActivity.startAct(activity, bleDevice);
            } else {
                new AlertDialog.Builder(getContext()).setTitle(R.string.start_dialog_title)
                        .setMessage(R.string.start_dialog_message)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                TestWaterActivity.startAct(activity, bleDevice);
                            }
                        })
                        .show();
            }
        } else if (MyApplication.selectCourse.equals(MyApplication.runningCourse)) {
            StartCourseActivity.startAct(activity, bleDevice);
        } else {
            new AlertDialog.Builder(getContext()).setTitle(R.string.other_course_run_title)
                    .setMessage(R.string.other_course_run_message)
                    .setNegativeButton(R.string.other_course_run_negative_btn, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            MyApplication.isTestWater = true;
                            StartCourseActivity.startAct(activity, bleDevice);
                        }
                    })
                    .setPositiveButton(R.string.other_course_run_positive_btn, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            startNewCourse(bleDevice);
                        }
                    })
                    .show();
        }
    }

    private void startNewCourse(final BleDevice bleDevice) {
        //先停止 正在运行的课程
        if (MyApplication.isTestWater) {
            bleStopCourse();
        } else {
            new AlertDialog.Builder(getContext()).setTitle(R.string.start_dialog_title)
                    .setMessage(R.string.start_dialog_message)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            TestWaterActivity.startAct(activity, bleDevice);
                        }
                    })
                    .show();
        }
    }

    private void bleStopCourse() {
        MySpUtils.putBoolean(MySpUtils.KEY_STAR_AUTO_INCREMENT, false);
        EventBusUtil.sendEvent(new EventBean(Constants.EVENT_STOP_COURSE));
        for (final BleDevice bleDevice : BleManager.getInstance().getAllConnectedDevice()) {
            BleUtils.write(bleDevice, BleUtils.getStopCourseCommand(), new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    StartCourseActivity.startAct(activity, bleDevice);
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        }
    }

    private void changeHomeFragmentUi() {
        ((MainActivity) getActivity()).goToFragment(0);
        Intent intent = new Intent("jerry");
        intent.putExtra("change", "yes");
        intent.putExtra("mLastCourseName", mLastCourseName);
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_GPS) {
//            if (Utils.checkGPSIsOpen(activity)) {
            scanBle();
//            }
        }
    }

    @Override
    public void onEventReceive(EventBean eventBean) {
        super.onEventReceive(eventBean);
        switch (eventBean.getCode()) {
            case Constants.EVENT_REFRESH_ELECTRIC:
                BleDataEvent bleDataEvent = (BleDataEvent) eventBean.getData();
                showElectric(bleDataEvent.getData(), bleDataEvent.getBleDevice());
                break;
            case Constants.EVENT_START_COURSE:
                mAdapter.notifyDataSetChanged();
                Utils.startKeepLive();
                break;
            case Constants.EVENT_STOP_COURSE:
                mAdapter.notifyDataSetChanged();
                Utils.stopKeepLive();
                break;
        }
    }
}
